package com.kasax.toolbox

import android.content.Context
import android.os.Environment
import com.google.gson.Gson
import com.kasax.base.BaseApp
import com.kasax.hilog.LogConfig
import com.kasax.hilog.LogLevel
import com.kasax.hilog.LogManager
import com.kasax.hilog.printer.ConsolePrinter
import com.kasax.hilog.printer.FilePrinter
import com.kasax.hilog.printer.ViewPrinter
import com.kasax.hinetwork.HttpApiManager
import com.kasax.hinetwork.StrategyConfig
import com.kasax.utils.FileUtil

class ToolboxApp : BaseApp() {
    override fun onCreate() {
        super.onCreate()
        initLogManager()
        initHttpNetAPI()
    }

    private fun initHttpNetAPI() {
        val strategyConfig = StrategyConfig()
        strategyConfig.coreType = StrategyConfig.CoreType.HTTP_URL_CONNECTION
        strategyConfig.connectTimeOut = 30 * 1000
        strategyConfig.readTimeOut = 30 * 1000
        strategyConfig.writeTimeOut = 30 * 1000
        HttpApiManager.getInstance().init(strategyConfig)
    }

    private fun initLogManager() {
        LogManager.init(
            object : LogConfig() {
                override fun getLogLevel(): LogLevel? = LogLevel.DEBUG

                override fun getLogTag(): String? = AppConstants.LOG_TAG

                override fun includeThreadInfo(): Boolean = true

                override fun includeStackTrace(): Boolean = true

                override fun enable(): Boolean = true
                override fun logFileCacheDirPath(): String? {
                    // 缓存到 /data/data/包名/cache/log
//                  return cacheDir.absolutePath
//                    return "${cacheDir.absolutePath}/log"

                    // 缓存到 /storage/emulated/0/log
//                    return "${externalCacheDir?.absolutePath}/log"
                    // 创建日志缓存的目录
//                    return FileUtil.createDir("${externalCacheDir?.absolutePath}/log")

                    // 缓存到 /storage/emulated/0/log
                    return FileUtil.createDir("${Environment.getExternalStorageDirectory()?.absolutePath}/log")
                }

                override fun injectAppContext(): Context? = applicationContext

                override fun injectJsonFrmatter(): JsonFormatter? {
                    return object : JsonFormatter() {
                        override fun format(obj: Any?): String {
                            return Gson().toJson(obj)
                        }
                    }
                }
            }, arrayOf(ConsolePrinter(), FilePrinter(), ViewPrinter())
        )
    }
}